const News = require('../models/news.model');

// 新
exports.create = function(req, res, next) {
  const news = new News(req.body);
  news.save().then(data => {
    res.json(data);
  });
};
// 删
exports.remove = function(req, res, next) {
  var id = req.params.id;
  News.findByIdAndDelete(id, (err, data) => {
    res.json(data);
  });
};

exports.removes = function(req, res, next) {
  var ids = req.body.ids.split(',');
  News.remove({ _id: { $in: ids } }).then(data => {
    res.json({ message: '数据删除成功', status: 200 });
  });
};


exports.nodeAnewsRemove = function(req, res, next) {
  var id = req.body.id
  queryCondition = {
    belong: new RegExp(id,'i')
  };
  News.remove(queryCondition).then(data => {
    res.json({ message: '数据删除成功', status: 200 });
  });
};

// 改
exports.update = function(req, res, next) {
  var id = req.params.id;
  News.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    // 千万小心，这里的data是没有更新之前的数据
    res.json(data);
  });
};

exports.getData = function(req, res, next) {
  var id = req.params.id;
  News.findById(id).then(data => {
    res.json(data);
  });
};

//查
exports.list = function(req, res, next) {
  // page
  // limit
  var page = req.body.page ? req.body.page : 1;
  var limit = req.body.rows ? req.body.rows : 5;

  var queryCondition = {};
  if (req.body.belong && req.body.belong.trim().length > 0) {
    belong = req.body.belong;
    queryCondition = {
      belong: new RegExp(belong,'i')
    };
  }
  if (req.body.title && req.body.title.trim().length > 0) {
    title = req.body.title;
    queryCondition = {
      title: new RegExp(title,'i')
    };
  }
  if (req.body.commentid && req.body.commentid.trim().length > 0) {
    commentid = req.body.commentid;
    queryCondition = {
      _id: commentid
    };
  }
  if(queryCondition.belong||queryCondition.title||queryCondition._id){
    News.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
      result.rows = result.docs;
      delete result.docs;
      res.json(result);
    });
  }else{
    News.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
      res.json([]);
    });
  }
  
};
